window.onload=function () {
    init();
    login();
}


Storage.prototype.setExpire = (key, value, expire) => {
    let obj = {
        data: value,
        time: Date.now(),
        expire: expire
    };
    //localStorage 设置的值不能为对象,转为json字符串
    localStorage.setItem(key, JSON.stringify(obj));
}

Storage.prototype.getExpire = key => {
    let val = localStorage.getItem(key);
    if (!val) {
        return val;
    }
    val = JSON.parse(val);
    if (Date.now() - val.time > val.expire) {
        localStorage.removeItem(key);
        return null;
    }
    return val.data;
}


function init() {
    $(".name input").focus(function(){
        $(this).prev("i").css({"background-image":"url(../assets/images/login_sys/user2.png)"});
    });
    $(".name input").blur(function(){
        $(this).prev("i").css({"background-image":"url(../assets/images/login_sys/user1.png)"});
    });
    $(".password input").focus(function(){
        $(this).prev("i").css({"background-image":"url(../assets/images/login_sys/password2.png)"});
    });
    $(".password input").blur(function(){
        $(this).prev("i").css({"background-image":"url(../assets/images/login_sys/password1.png)"});
    });
    document.onkeydown = function (e) { // 回车提交表单
        var theEvent = window.event || e;
        var code = theEvent.keyCode || theEvent.which;
        if (code == 13) {
            $("#login-btn").click(); // #chk_match 是你 提交按钮的ID
        }
    }
}

var key = CryptoJS.enc.Utf8.parse("cBssbHB3ZA==HKXT");
function aesEncode(str) {
    var encryptedData = CryptoJS.AES.encrypt(str, key, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
    });
    return encryptedData.toString();
}

//登录
function login() {
    layui.use(['layer', 'form'], function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;

        //自定义验证规则
        form.verify({
            username: function(value){
                if(value.length < 2){
                    return '用户名至少得2个字符';
                }
            }
            ,password: [
                /^[\S]{2,18}$/
                ,'密码必须2到18位，且不能出现空格'
            ]
        });

        // 表单提交
        form.on('submit(login-submit)', function (obj) {
            var user = obj.field;
            var formData = new FormData();
            // 加密用户名密码
            var  suff = new Date().getMilliseconds();
            formData.append("username",aesEncode(user.username) + "_" + suff);
            formData.append("password",aesEncode(user.password) + "_" + suff);
            // formData.append("username",user.username);
            // formData.append("password",user.password);
            formData.append("client_id","cloud");
            formData.append("client_secret","cloud");
            formData.append("grant_type","password");
            axios({
                method: 'post',
                url:loginUrl.tokenUrl,
                data:formData,
                headers:{
                    'Content-Type':'application/x-www-form-urlencoded'}
            })
            .then(function (response) {
                if(response.status == 200){
                    var data = response.data;
                    localStorage.setExpire('access_token',data.access_token,sysTimeOut);
                    localStorage.setExpire("token_type",data.token_type,sysTimeOut)
                    getUserInfo();
                }
            })
            .catch(function (error) {
                console.log(error);
                layer.msg(error.response.data.message, {icon: 2, time: 1500});
            });
            return false;
        });

    });

}


// 获取用户信息
function getUserInfo() {
    var access_token = localStorage.getExpire("access_token");
    axios.get(loginUrl.userInfo,{
        params: {
            access_token: access_token
        }
    })
    .then(function (response) {
        if(response.status == 200 &&response.data.message == "success"){
            localStorage.setExpire("userInfo",JSON.stringify(response.data.data),sysTimeOut)
            getMenuTree();
        }
    })
    .catch(function (error) {
        console.log(error);
        if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
            // 进行重新登陆
            localStorage.clear();
            top.location.href=loginPageUrl;
        }
    });
}
// 获取左边树
function getMenuTree() {
    var access_token = localStorage.getExpire("access_token");
    var token_type = localStorage.getExpire("token_type");
    var Authorization = token_type+" "+access_token;
        let req = {
            system_identifier:'system_data'
        }
        axios({
            method: 'get',
            url:loginUrl.menuTree,
            params:req,
            headers:{
                'Authorization':Authorization}
        })
        .then(function (response) {
            if(response.status == 200){
                var data = response.data;
                localStorage.setExpire("menuTree",JSON.stringify(data.data),sysTimeOut)
                location.href=webBaseUrl+'/index.html';
            }
        })
        .catch(function (error) {
            console.log(error);
            if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                // 进行重新登陆
                localStorage.clear();
                top.location.href=loginPageUrl;
            }
        });
}